package com.gxm.练习.多线程.循环abc;

/**
 * @创建人 郭训民
 * @创建时间 2019/11/15
 * @描述 三个线程 循环输出 abcabcabc
 */
public class Abc {
    String flag = "a" ;
    public synchronized void printlA() throws InterruptedException {
        while (true){
            if (flag == "a"){
                System.out.println("a");
                Thread.sleep(1000);
                flag = "b";
                notifyAll();
            }
            wait();
        }
    }
    public synchronized void printlB() throws InterruptedException {
        while (true){
            if (flag == "b"){
                System.out.println("b");
                Thread.sleep(1000);
                flag = "c";
                notifyAll();
            }
            wait();
        }
    }
    public synchronized void printlC() throws InterruptedException {
        while (true){
            if (flag == "c"){
                System.out.println("c");
                Thread.sleep(1000);
                flag = "a";
                notifyAll();
            }
            wait();
        }
    }

    public static void main(String[] args) {
        Abc abc = new Abc();
        PrintA printA = new PrintA(abc);
        PrintB printB = new PrintB(abc);
        PrintC printC = new PrintC(abc);
        Thread t1 = new Thread(printA);
        Thread t2 = new Thread(printB);
        Thread t3 = new Thread(printC);
        t1.start();
        t2.start();
        t3.start();
    }
}


class PrintA implements Runnable{
    private Abc abc;
    public PrintA(Abc abc){
        this.abc = abc;
    }
    @Override
    public void run() {
        try {
            abc.printlA();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class PrintB implements Runnable{
    private Abc abc;
    public PrintB(Abc abc){
        this.abc = abc;
    }
    @Override
    public void run() {
        try {
            abc.printlB();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class PrintC implements Runnable{
    private Abc abc;
    public PrintC(Abc abc){
        this.abc = abc;
    }
    @Override
    public void run() {
        try {
            abc.printlC();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}